package com.sd.repay.utils;

import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.security.Key;
import java.util.Random;

/**
 * 描述：3DES
 * <p>
 * 创建时间：2018年08月31日
 */

public abstract class DES3Coder {

    private static final String KEY_ALGORITHM = "DESede";
    private static final String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";
    private static final String KEY = "h5dI9.%85f?kof3nV[1.`jh3";

    /**
     * 功能：获取密钥
     *
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] initKey(String key) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        kg.init(168);
        SecretKey secretKey = kg.generateKey();
        return secretKey.getEncoded();

    }

    /**
     * 功能：密钥转换
     *
     * @param key
     * @return
     * @throws Exception
     */
    private static Key toKey(byte[] key) throws Exception {
        DESedeKeySpec dks = new DESedeKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generateSecret(dks);
    }

    /**
     * 功能：
     *
     * @param data 密文
     * @param key  密钥
     * @return 解密数据
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        //还原密钥
        Key k = toKey(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        //初始化,设置加密模式
        cipher.init(Cipher.DECRYPT_MODE, k);
        //解密操作
        return cipher.doFinal(data);

    }


    /**
     * 功能：
     *
     * @param data 明文
     * @param key  密钥
     * @return 加密数据
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        //还原密钥
        Key k = toKey(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        //初始化,设置加密模式
        cipher.init(Cipher.ENCRYPT_MODE, k);
        //加密操作
        return cipher.doFinal(data);

    }


    /**
     * 功能：加密成十六进制字符串
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String encryptToString(String data) {
        String random = getRandomString(6);
        data = data + random;
        byte[] securityByte;
        try {
            securityByte = encrypt(data.getBytes("UTF8"), KEY.getBytes("UTF8"));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return HexDump.toHexString(securityByte) + random;
    }

    public static String decryptToString(String securityData) throws Exception {
        if (securityData.length() < 6) {
            return "";
        }
        securityData = securityData.substring(0, securityData.length() - 6);
        byte[] securityByte = HexDump.hexStringToByteArray(securityData);
        byte[] clearByte = decrypt(securityByte, KEY.getBytes("UTF8"));
        String clearData = new String(clearByte, "UTF8").toString();
        if (clearData.length() < 6) {
            return "";
        }
        return clearData.substring(0, clearData.length() - 6);

    }

    /**
     * 功能：校验明文密文是否一致
     *
     * @param clearData    明文
     * @param securityData 密文
     * @return
     */
    public static boolean verify(String clearData, String securityData) {
        System.out.println("进入密文校验");

        if (StringUtils.isBlank(securityData) || securityData.length() < 6) {
            return false;
        }
        String decryptSecurityData = "";
        try {
            decryptSecurityData = decryptToString(securityData);
        } catch (Exception e) {
            return false;
        }
        return decryptSecurityData.equals(clearData);

    }

    /**
     * 功能：产生n位随机字符
     *
     * @return
     */
    private static String getRandomString(int len) {

        String f = "0123456789abcdef";
        String ret = "";
        for (int i = 0; i < len; i++) {
            Random random = new Random();
            int num = random.nextInt();
            num = num % 16;
            if (num < 0) {
                num = (-num);
            }
            if (i == 0) {
                ret = "" + f.charAt(num);
            } else {

                ret += f.charAt(num);
            }
        }
        return ret.toUpperCase();
    }
}
